package com.mox.enterprise.util;

import com.mox.enterprise.constants.JedisConfig;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author mox
 * @time 2020/2/18 15:24
 */
@Slf4j
public class JedisUtil {

    private static JedisPool jedisPool = null;

    // 初始化Redis连接池
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(JedisConfig.MAX_ACTIVE);
            config.setMaxIdle(JedisConfig.MAX_IDLE);
            config.setMaxWaitMillis(JedisConfig.MAX_WAIT);
            config.setTestOnBorrow(JedisConfig.TEST_ON_BORROW);
            jedisPool = new JedisPool(config,
                    JedisConfig.IP_ADDRESS, JedisConfig.PORT,
                    JedisConfig.TIMEOUT, JedisConfig.AUTH, JedisConfig.DEFAULT_DATABASE);
        } catch (Exception e) {
            log.info("redis初始化失败:{}", e.getMessage());
        }

    }

    /**
     * 获取Jedis实例
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                log.info("redis--服务正在运行: " + resource.ping());
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 释放资源
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

}
